// --------------- 高阶函数 ---------------------
def f(x: Int, y: Int) = x + y ;

// f是函数类型的变量 传入两个Int个的参数，返回Int类型的数据
def operate(f: (Int, Int) => Int) : Int = {
  f(4, 5);
}

operate(f: (Int, Int) => Int);

operate(f: (Int, Int) => Int);

// f是函数类型的变量 传入两个Int个的参数，返回Int类型的数据
def operate(f: (Int, Int) => Int, x:Int) : Int = {
  f(4, 5) + x;
}

operate(f: (Int, Int) => Int, 5);

// f是函数类型的变量 传入两个Int个的参数，返回Int类型的数据
def operate(f: (Int, Int) => Int, x:Int, y:Int) : Int = {
  f(x, y);
}

operate(f: (Int, Int) => Int, 5, 6);

// ---------------- 匿名行数 --------------------
def greeting = (name: String) => {"hello " + name}

greeting("张三")

// ----------------- 柯里化  -----------------------
def add(x: Int, y: Int) = x + y
def add1(x: Int)(y: Int) = x + y

add(1,2)
add1(3)(5)

def curriedAdd(a: Int)(b: Int) = a + b ;

// 动态匹配
val addOne = curriedAdd(1)_
addOne(2)

// ------------------ 递归与尾递归 ------------------------
def factorial(n: Int) : Int = {
  if (n <= 0) 1
  else n * factorial(n-1) ;
}

factorial(5)

// 该尾递归将每次计算的值存到m中，m中保存着上一次计算的结果
def factorial(n: Int, m: Int) : Int = {
  if (n <= 0) m
  else factorial(n-1, m * n) ;
}

factorial(5, 1)


// 函数综合示例应用
def sum(f: Int => Int)(a: Int)(b: Int): Int = {
  @annotation.tailrec
  def loop(n: Int, acc: Int) : Int = {
    if (n > b) {
      println(s"n=${n},acc=${acc}")
      acc
    }else {
      println(s"n=${n},acc=${acc}")
      loop(n+1, acc + f(n))
    }
  }

  loop(a, 0)
}

sum(x => x)(1)(5)

sum(x => x * x)(1)(5)

sum(x => x * x * x)(1)(5)

var sumSquare = sum(x => x * x)_
sumSquare(1)(5)